/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */
package edu.uc.labs.MobilePrinting.Fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import static edu.uc.labs.MobilePrinting.Configurator.*;

/**
 * @author Matt Silbernagel
 *
 */
public class XSDFetcher {

	private String input;
	private String resource = "/resources/" + XMLVALIDATE;
	private String url ;
	private URL u;
	private URLConnection conn;
	
	public XSDFetcher() throws ConnectException, IOException{
		buildURL();	
		connect();
	}
	
	/**
	 * Get the string that is the XSD
	 * @return XSD
	 */
	public String getResponse(){
		return input;
	}
	
	/**
	 * Build the URL to get the XSD
	 * @throws MalformedURLException
	 */
	private void buildURL() throws MalformedURLException {
		// Build the URL
		url = "http://" + HTTP_SERVER + resource;
		u = new URL(url);
	}
	
	/**
	 * Connect and download the XSD
	 * @throws IOException
	 * @throws ConnectException
	 */
	private void connect() throws IOException, ConnectException {
		LOGGER.debug("The URL to send: " + u.toString());
		conn = u.openConnection();
		InputStream instream = conn.getInputStream();
		Scanner in = new Scanner(instream);
		while (in.hasNextLine()) {
			input += in.nextLine() + "\n";
		}

	}
}
